import React from "react";
import BoilingVerdict from './BoilingVerdict'
import TemperatureInput from './TemperatureInput'

type P = {}

type S = {
    scale: string;
    temperature: string;
}

function toCelsius(fahrenheit: number) {
    return (fahrenheit - 32) * 5 / 9;
}

function toFahrenheit(celsius: number) {
    return (celsius * 9 / 5) + 32;
}

function tryConvert(temperature: string, convert: (n: number) => number) {
    const input = parseFloat(temperature);
    if (Number.isNaN(input)) {
        return '';
    }
    const output = convert(input);
    const rounded = Math.round(output * 1000) / 1000;
    return rounded.toString();
}

export default class Calculator extends React.Component<P, S> {
    constructor(props: P) {
        super(props);
        this.state = {
            scale: 'c',
            temperature: ''
        };
    }
    handleChange = (temperature: string, scale: string) => {
        this.setState({ temperature, scale });
    }
    render() {
        const scale = this.state.scale;
        const temperature = this.state.temperature;
        const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
        const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
        return (
            <div>
                <TemperatureInput temperature={celsius} onChange={this.handleChange} scale="c" />
                <TemperatureInput temperature={fahrenheit} onChange={this.handleChange} scale="f" />
                <BoilingVerdict celsius={parseFloat(celsius)} />
            </div>
        );
    }
}